package whf.framework.workflow.context;

import java.io.IOException;
import java.io.Serializable;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.jbpm.JbpmConfiguration;
import org.jbpm.JbpmContext;

import whf.framework.security.UserContext;
import whf.framework.security.entity.User;
import whf.framework.web.WebContextHolder;

/**
 * @author King
 *
 */
public class WorkflowContextFilter implements Filter, Serializable {

	private static final long serialVersionUID = 1L;

	String jbpmConfigurationResource = null;
	String jbpmContextName = null;
	boolean isAuthenticationEnabled = true;

	public void init(FilterConfig filterConfig) throws ServletException {
		// get the jbpm configuration resource
		this.jbpmConfigurationResource = filterConfig.getInitParameter("jbpm.configuration.resource");

		// get the jbpm context to be used from the jbpm configuration
		this.jbpmContextName = filterConfig.getInitParameter("jbpm.context.name");
		if (jbpmContextName == null) {
			jbpmContextName = JbpmContext.DEFAULT_JBPM_CONTEXT_NAME;
		}
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException,
			ServletException {
		User actor = null;
		// see if we can get the authenticated swimlaneActorId
		if (servletRequest instanceof HttpServletRequest) {
			HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
			UserContext userContext = WebContextHolder.getWebContext(httpServletRequest).getUserContext();
			actor = userContext.getUser();
		}

		if (actor != null) {
			JbpmContext jbpmContext = getJbpmConfiguration().createJbpmContext(jbpmContextName);
			try {
				jbpmContext.setActorId(actor.getUsername());
				filterChain.doFilter(servletRequest, servletResponse);
			} finally {
				jbpmContext.close();
			}
		} else {
			filterChain.doFilter(servletRequest, servletResponse);
		}
	}

	protected JbpmConfiguration getJbpmConfiguration() {
		return JbpmConfiguration.getInstance(jbpmConfigurationResource);
	}

	public void destroy() {
	}
}